using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;


public class MixerHandler : LightRayHandler {
	
	public GameObject objToColor;
	
	private bool isTriggered = false;
	
	private Dictionary<Color,float> listColors = new Dictionary<Color, float>();
	private List<Color> toRemove = new List<Color>();
	
	public override void initialize(int id, Vector3 position, float rotation, Color c, bool fixedObj){
		Type = ObjectType.Mixer;
		
		LevelConstants.nbMixer++;
		
		c = new Color(c.r,c.g,c.b,0.8f);
		objToColor.renderer.material.SetColor("_Color",c);
		
		base.initialize(id, position, rotation, c, fixedObj);

	}
	
	public override List<LightHitInfo> getNextLightRay(LightHitInfo hitInfo){
		List<LightHitInfo> newRays = new List<LightHitInfo>();
		
		if(listColors.ContainsKey(hitInfo.LightColor)){
			listColors[hitInfo.LightColor] = Time.time;
		}else{
			listColors.Add(hitInfo.LightColor, Time.time);
		}
		
		
		if(!isTriggered){
			LightHitInfo newRay = new LightHitInfo(hitInfo);
			newRay.Point = transform.position;
			newRay.Direction = Quaternion.AngleAxis(45,Vector3.forward) * transform.right;
			currentColor = ColorUtils.addColors(listColors.Keys.ToArray());
			
			newRay.LightColor = currentColor;
			
			currentColor = new Color(currentColor.r,currentColor.g,currentColor.b,0.8f);
			
			
			objToColor.renderer.material.SetColor("_Color",currentColor);
			
			newRays.Add(newRay);
			
			for(int i = 0; i<3; i++){
				newRay = new LightHitInfo(newRay);
				newRay.Direction = Quaternion.AngleAxis(90,Vector3.forward) * newRay.Direction;
				newRays.Add(newRay);
			}
			
			isTriggered = true;
		}else{
			hitInfo.Direction = Vector3.zero;
			newRays.Add(hitInfo);
		}
			
		return newRays;	
	}

	
	void LateUpdate(){
		toRemove.Clear();
		
		foreach(KeyValuePair<Color,float> entry in listColors){
			if(Time.time - entry.Value > Time.deltaTime){
				toRemove.Add(entry.Key);
			}
		}
		
		foreach(Color c in toRemove){
			listColors.Remove(c);	
		}
		
		if(!isTriggered){
			currentColor = Color.white;
			currentColor = new Color(currentColor.r,currentColor.g,currentColor.b,0.8f);	
		}
		
		objToColor.renderer.material.SetColor("_Color",currentColor);
		
			
		
		
		isTriggered = false;	
	}
	
	void OnDestroy(){
		LevelConstants.nbMixer--;	
	}
}